from pdf2docx import Converter
import PySimpleGUI as sg

def pdf2word(file_path):
    file_name = file_path.split('.')[0]
    doc_file = f'{file_name}.docx'
    p2w = Converter(file_path)
    p2w.convert(doc_file, start=0, end=None)
    p2w.close()
    return doc_file

def main():
    sg.theme('LightBlue5')

    layout = [
        [sg.Text('请选择一个或多个PDF文件', font=('微软雅黑', 12)), sg.Text('', key='filename', size=(50, 1), font=('微软雅黑', 10), text_color='blue')],
        [sg.Output(size=(80, 10), font=('微软雅黑', 10))],
        [sg.FilesBrowse('选择PDF文件', key='file', target='filename'), sg.Button('转换为docx'), sg.Button('Exit')]
    ]
        # create window
    window = sg.Window('转换为docx', layout, font=('微软雅黑', 15), default_element_size=(50,10))
        # loop event
    while True:
            # 窗口的读取，有2个返回值（1.时间，2.值）
            event, values = window.read()
            print(event, values)

            if event == '转换为docx':

                if values['file'] and values['file'].split('.')[1] == 'pdf':
                    filename = pdf2word(values['file'])
                    print('Number of files: 1')
                    print('\n' + 'Conversion succeeded!' + '\n')
                    print('File save location: ', filename)
                elif values['file'] and values['file'].split(';')[0].split('.')[1] == 'pdf':
                    print('Number of files: {}'.format(len(values['file'].split(';'))))
                    for f in values['file'].split(';'):
                        filename = pdf2word(f)
                        print('\n' + 'Conversion succeeeded!' + '\n')
                        print('File save location: ', filename)
                else:
                    print('Please select pdf file')
            if event in (None, 'Exit'):
                break

            window.close()

main()

# 生成exe文件
# pyinstaller -F -w demo.py
